package TCP.EchoServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpThreadEchoServer {

    private ServerSocket serverSocket = null;

    public TcpThreadEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("启动服务器!");

        while (true) {
            // 先建立连接,如果没有客户端请求建立连接,就会阻塞
            Socket clientSocket = serverSocket.accept();
            // 后续的沟通都是通过 clientSocket 来处理
            // 使用多线程
            Thread t = new Thread(() -> {
                processConnection(clientSocket);
            });
            t.start();
        }
    }
    public void processConnection(Socket clientSocket){
        System.out.printf("[%s:%d]客户端建立连接\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //处理请求
        try(InputStream inputStream = clientSocket.getInputStream()) {
            try(OutputStream outputStream = clientSocket.getOutputStream()) {
                // 循环处理每个请求  -- 读取请求
                Scanner scanner = new Scanner(inputStream);
                while (true) {
                    if (!scanner.hasNext()){
                        System.out.printf("[%s:%d]客户端断开连接\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                        break;
                    }
                    String request = scanner.next();
                    // 计算响应
                    String response = process(request);
                    // 可以使用 PrintWriter 将outputStream包裹一下
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);
                    printWriter.flush();//刷新
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String process(String request){
        return request;
    }


    public static void main(String[] args) throws IOException {
        TcpThreadEchoServer server = new TcpThreadEchoServer(9090);
        server.start();
    }
}
